package com.uls.ycl.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.uls.common.core.domain.AjaxResult;
import com.uls.common.core.domain.entity.SysUser;
import com.uls.system.service.ISysUserService;
import com.uls.ycl.domain.RepairMaterial;
import com.uls.ycl.mapper.RepairMaterialMapper;
import com.uls.ycl.service.IRepairMaterialService;
import com.uls.ycl.vo.TaskCommentVo;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uls.ycl.mapper.RepairItemMapper;
import com.uls.ycl.domain.RepairItem;
import com.uls.ycl.service.IRepairItemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报修项目Service业务层处理
 * 
 * @author ycl
 * @date 2024-11-18
 */
@Service
public class RepairItemServiceImpl implements IRepairItemService 
{
    @Autowired
    private RepairItemMapper repairItemMapper;


    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private ISysUserService userService;  //取用户名
    @Autowired
    private RepairMaterialMapper repairMaterialMapper;
    @Autowired
    private IRepairMaterialService repairMaterialService;
    /**
     * 查询报修项目
     * 
     * @param itemId 报修项目主键
     * @return 报修项目
     */
    @Override
    public RepairItem selectRepairItemByItemId(Long itemId)
    {
        return repairItemMapper.selectRepairItemByItemId(itemId);
    }

    /**
     * 查询报修项目列表
     * 
     * @param repairItem 报修项目
     * @return 报修项目
     */
    @Override
    public List<RepairItem> selectRepairItemList(RepairItem repairItem)
    {
        return repairItemMapper.selectRepairItemList(repairItem);
    }

    /**
     * 新增报修项目
     * 
     * @param repairItem 报修项目
     * @return 结果
     */
    @Override
    public int insertRepairItem(RepairItem repairItem)
    {

        return repairItemMapper.insertRepairItem(repairItem);
    }

    /**
     * 修改报修项目
     * 
     * @param repairItem 报修项目
     * @return 结果
     */
    @Override
    public int updateRepairItem(RepairItem repairItem)
    {

        return repairItemMapper.updateRepairItem(repairItem);
    }

    /**
     * 批量删除报修项目
     * 
     * @param itemIds 需要删除的报修项目主键
     * @return 结果
     */
    @Override
    public int deleteRepairItemByItemIds(Long[] itemIds)
    {
        return repairItemMapper.deleteRepairItemByItemIds(itemIds);
    }

    /**
     * 删除报修项目信息
     * 
     * @param itemId 报修项目主键
     * @return 结果
     */
    @Override
    public int deleteRepairItemByItemId(Long itemId)
    {
        return repairItemMapper.deleteRepairItemByItemId(itemId);
    }


    /**
     * 启动流程
     *
     * @param
     * @param userId
     */
    @Override
    @Transactional
    public int submit(Long itemId, Long userId) {
        RepairItem item = repairItemMapper.selectRepairItemByItemId(itemId);

        String processDefiKey = "myitem";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 143);  //先写死，是副总的编号
        //没有启动这个流程
        if (item.getStatus() == 0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            item.setFlowInstantId(Long.parseLong(pi.getProcessInstanceId()));  // 把流程实例id与业务系统绑定
            item.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee("" + userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());

            return repairItemMapper.updateRepairItem(item);
        }
        //流程启动了，打回重新审批，就不用再启动流程
        else {

            Long flowInstantId = item.getFlowInstantId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstantId)
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            item.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return repairItemMapper.updateRepairItem(item);
        }


    }


    //查询不带条件提交申请但未审批的项目信息
    @Override
    @Transactional
    public List<RepairItem> noFinishTask(Long userId, String processDefiniionKey) {
        List<RepairItem> listItem = new ArrayList<RepairItem>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("报修项目申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    //根据流程id查询学生mapper的方法
                    RepairItem item = repairItemMapper.selectRepairItemFlowId(flowInstanceId);
                    listItem.add(item);
                }

            }
        }

        return listItem;
    }


    //带条件查询提交申请但未审批的学生信息
    @Override
    @Transactional
    public List<RepairItem> noFinishTask(Long userId, String processDefiniionKey, RepairItem item) {
        List<RepairItem> listItem = new ArrayList<RepairItem>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefiniionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("报修项目申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    item.setFlowInstantId(flowInstanceId);
                    //根据流程id和其他条件查询老师mapper的方法
                    RepairItem item1 = repairItemMapper.selectRepairItemFlowIdOther(item);
                    if (item1 != null)
                        listItem.add(item1);
                }

            }
        }

        return listItem;
    }


    //审批
    @Override
    @Transactional
    public void completeTask(Long flowInstantId, Integer agree, Long userId, String comment, Long itemId) {
        RepairItem item = repairItemMapper.selectRepairItemByItemId(itemId);

        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstantId)
                .list();
        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();

        if (list != null && list.size() > 0) {
            for (Task task : list) {

                if (task.getName().equals("副总审批")) {
                    if (agree == 1) {
                        params.put("inputUser3", 144);  //固定一个人员4
                        item.setStatus(2l);//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    } else {
                        item.setStatus(1l);
                    }
                    params.put("pass1", agree);  //给流程变量赋值

                } else if (task.getName().equals("总经理审批")) {
                    if (agree == 1) {
                        item.setStatus(3l);
                        //同时材料库对应的数量减少
                        item.setUpdateAt(new Date());

                        RepairMaterial material = repairMaterialMapper.selectRepairMaterialByMaterialId(item.getMaterialId());
                        material.setTotal(material.getTotal() - item.getTotal());

                        repairMaterialService.updateRepairMaterial(material);
                    } else {
                        item.setStatus(1l);
                    }
                    params.put("pass2", agree);  //给流程变量赋值
                }

                repairItemMapper.updateRepairItem(item);

                // 添加批注时候的审核人，通常应该从session获取,现在从redis
                Authentication.setAuthenticatedUserId(userId.toString());

                if (comment == null) {
                    comment = ""; // 设置默认评论
                }
                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);
                // taskId：任务id
                taskService.complete(task.getId(), params);


            }
        }

    }

    //查询审批历史
    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstantId) {

        List<TaskCommentVo> taskCommentVoList = new ArrayList<>();

        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments("" + flowInstantId);

        for (Comment com : list) {
            TaskCommentVo taskCommentVo = new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());

            SysUser user = userService.selectUserById(Long.parseLong(com.getUserId()));  //查询用户名

            taskCommentVo.setUserName(user.getUserName());


            //从历史任务取数据
            List<HistoricTaskInstance> hist = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId("" + flowInstantId)
                    .taskId(com.getTaskId())
                    .list();
            if (hist != null && hist.size() > 0) {
                HistoricTaskInstance historicTaskInstance = hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());

                taskCommentVo.setEndtime(historicTaskInstance.getEndTime());

            }

            taskCommentVoList.add(taskCommentVo);

        }


        //排序
        List<TaskCommentVo> taskCommentVoListSort = new ArrayList<>();

        for (int i = taskCommentVoList.size() - 1; i >= 0; i--) {
            TaskCommentVo temp = taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }

        return taskCommentVoListSort;
    }

    //已完成的任务
    @Override
    public List<RepairItem> finishedTask(Long userId, String processDefiniionKey, RepairItem item) {
        List<RepairItem> listFinishedItem = new ArrayList<RepairItem>();
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefiniionKey)
                .processFinished()
                .list();
        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance hti : list) {
                if (!hti.getName().equals("报修项目申请111")) {
                    Long flowInstanceId = Long.parseLong(hti.getProcessInstanceId());
                    item.setFlowInstantId(flowInstanceId);
                    RepairItem item1=repairItemMapper.selectRepairItemFlowIdOther(item);
                    if (item1!=null)
                        listFinishedItem.add(item1);
                }


            }
        }
        //去重
        List<RepairItem> listFinishedItem1 = new ArrayList<>(new HashSet<>(listFinishedItem));
            return listFinishedItem1;
        }


}
